<?php

namespace App\Repository\Repositories;
use App\Helpers\Code;
use App\Helpers\Face;
use App\Helpers\Image;
use App\Helpers\Token;
use App\Http\Controllers\Controller;
use App\Http\Service\Redisd;
use App\Models\User;
use App\Models\WechatUser;
use App\Repository\RepositoryInterface\UserLoginInterface;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class UserLoginRepositories extends Controller implements UserLoginInterface
{
    protected $user;
    public function __construct(User $user)
    {
        $this->user=$user;
    }
    public function perDetails($uid)
    {
        return WechatUser::with(['systemStoreStaff','systemStoreStaff.systemStore'])->where('uid', $uid)->first();
    }

    /**
     * @param $phone @用户登录注册获取验证码的手机号
     *
     */
    public function sendCode($phone)
    {
        $validator = Validator::make(['phone'=>$phone], [
            'phone' => 'regex:/^1[3456789]\d{9}$/|required',
        ]);

        if($validator->fails()){
            return parent::error('手机号格式不正确或者为空',[]);
        }

        $result=Redis::exists($phone.'last_time');
        if($result !=0 ){
            $lastTime=Redisd::getInstance()->get($phone.'last_time');
            if(time()-$lastTime < 180){
                return  parent::error('3分钟之内请勿重复发送',[]);
            }
        }
        $code=rand(1000,9999);
        $res=(new Code())->getCode($phone,$code,'',md5(''));
        if($res != "短信发送成功"){
            return parent::error($res,[]);
        }
        Redisd::getInstance()->set($phone.'code',$code,300);
        Redisd::getInstance()->set($phone.'last_time',time());
        return  parent::success('发送成功',[]);
    }

    /**
     * @param $data
     * 用户注册方法
     */
    public function userRegister ($data)
    {
        $result=Redis::exists($data['phone'].'code');
        if($result != 0){
            $code=Redisd::getInstance()->get($data['phone'].'code');
            if($code != $data['code']){
                return  parent::error('验证码有误',[]);
            }
            //验证码正确 判断手机号是否存在
            $user_data=User::where('phone',$data['phone'])->first();
            if(!empty($user_data)){
                return parent::error('手机号已经注册过账号',[]);
            }
            $data['password']=bcrypt($data['password']);
            unset($data['code']);
            try {
                $res=User::create($data);
                Redisd::getInstance()->del($data['phone'].'code');
                return parent::success('注册成功',[]);
            }catch (QueryException $queryException){
                return  parent::error($queryException->getMessage(),[]);
            }

        }
        return parent::error('验证码失效,请重新获取',[]);
    }

    /**
     * @param $data
     * 校验账号密码
     */
    public function verify($data)
    {
        $validator=Validator::make($data,[
            'account'=>'required',
            'password'=>'required'
        ]);
        if($validator->fails()){
            return  parent::error('账号或者密码不能为空',[]);
        }
        $bool=Auth::attempt($data);
        if(!$bool){
            return parent::error('账号或密码有误',[]);
        }
        $user_data=User::where('account',$data['account'])->first();
        $jwtToken=Token::createToken($user_data->uid);
        return  success('登录成功',$jwtToken,200);
    }

    /**
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     * 修改用户信息
     */
    public function upUserInfo($data,$uid)
    {
        if(empty($data['pay_pass'])){
            unset($data['pay_pass']);
        }else{
            $validator=Validator::make($data,[
                'pay_pass'=>'regex:/^\d{6}$/'
            ],[
                'pay_pass.regex'=>'支付密码格式不正确'
            ]);
            if(!$validator->fails()){
                $data['pay_pass']=md5($data['pay_pass']);
            }
            return  fails('支付密码格式不正确',[],500);
        }
        try {
            User::where('uid',$uid)->update($data);
            return  success('用户信息修改成功',[],200);
        }catch (QueryException $queryException){
            return parent::error($queryException->getMessage());
        }
    }

    /**
     * @param $uid
     * @return \Illuminate\Http\JsonResponse
     * 查询修改用户信息
     */
    public function findUser($uid)
    {
        try {
            $user_data=User::findUser($uid)->toarray();
            return parent::success('获取成功',$user_data);
        }catch (QueryException $queryException){
            return parent::error($queryException->getMessage());
        }
    }

    /**
     * @param $file @上传头像
     */
    public function changeAvatar($file,$uid){
        $res=(new Image())->uploadFile($file,'pg9BrXIoZynp783RA7MkhMWgsL31QmMbsp6X6JPx','4GbfszhdWNM-4FDsgVh-l7rcxVukh3I-Erwa1DAu','yisheng','http://ys.yscool.work/');
        if(is_string($res)){
            try {
                User::where('uid',$uid)->update(['avatar'=>$res]);
                return success('上传成功',$res,200,JSON_UNESCAPED_UNICODE);
            }catch (QueryException $queryException){
                return  fails('修改失败',[],500);
            }
        }
        return  $res;
    }

    /**
     * @param $uid
     * @return \Illuminate\Http\JsonResponse
     * 查询该用户的信息zyy
     */
    public function findUserData($uid){
        //参数判断
        if (!is_numeric($uid) || $uid == '') {
            return parent::error('参数格式不正确', '');
        }
        try {
            $userData = $this->user->where("uid",$uid)->first();
            return parent::success("该用户是".$userData->real_name,$userData);
        }catch (\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }

    /**
     * @param $file
     * @param $uid
     * @return array
     * @throws \Exception
     * 人脸识别
     */
    public function face($file,$uid)
    {
        //上传图片地址
        $res = (new Image())->uploadFile($file, 'pg9BrXIoZynp783RA7MkhMWgsL31QmMbsp6X6JPx', '4GbfszhdWNM-4FDsgVh-l7rcxVukh3I-Erwa1DAu', 'yisheng', 'http://ys.yscool.work/');
        //认证的图片地址
        $user_data=User::where('uid',$uid)->first()->toarray();
        $result=Face::getToken();
        $token=$result['access_token'];
        $result=Face::compareFace($token,$res,$user_data['faceUrl']);
        $result=json_decode($result,true);
        if($result['result']['score']>80){
            return  success('对比成功',[],200);
        }else{
            return error('人脸对比失败',[],500);
        }
    }
}
